import { defHttp } from '/@/utils/http/axios';
import { useGlobSetting } from '/@/hooks/setting';
import { JSEncrypt } from 'encryptlong';
import { AesEncryption } from './cipher';
const glob = useGlobSetting();
import { Memory } from './cache/memory';
const localMemory = new Memory(60 * 60 * 24 * 24);

const aesParams = { key: 'qA0pBkQGERsM4Zqh', iv: 'ghdQkz8En8bHGeM3' };
export const initSecretInfo = async (encryptSecretInfo) => {
  let privateKey = `-----BEGIN PRIVATE KEY-----
  MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBANxnROAUv5QmUjMiAbwojuOF4+7iM47TYupbnp3coxba4SQD1G7/G5tUVl2cz0Wnv7+leDrah6naMkzy2XTGTwrilTI73B+XU63LkUWUF80PYRAVljA2TqAry2HC0eh66G3RrlZnu72MYrLRhWbOO0shsQzUTXfZmlYLvXm9/377AgMBAAECgYBJKGgWvxxWNyAaw+Nyir3fLM6bOO8nLehL5Sxxts5VpEKN+010qG4H8YcXXJj6RHOjz+9oDahxSzFeFE/08GxEkSw/LOMR06Wc4rFv8M5u0D3y8CyjVixzsIezwsUH2FBllrb86j5GPmMdoQS168ob1IHgZ0bu38UB9SPGa9cNjQJBAP1CLSsgyaWEmFhNv7TIqYZADtrqRXS2SnTXB96a6SuOclDM/1r9xRa95uZlcpf2Hg0PCd7S3wLC1Hu0ldPp7gcCQQDeyguc4Gu2lgf0UnGHLy5Iq9mcKhuGpQdJGvWRVW23IfF8xC7INqdf5dDXhVaAC3shyAqnTHO5yxmHoqc06CptAkAkcdx8I1jBR+aAdpfK1UGH/znkCOh71iu6yqLoRtSdHv+WXxm0J2awUh2jNCAcfB9w86QQ+7l59T2Mm70f5L8LAkEAnAjOEVVsmziA4bFMKe31cJhLlIA5Pxgd/imPi/ZVHUn8o/GTAk6k8xk2J3wPlSZ1WreMHpgBBUMl4kUc7oUcEQJAcI9ED97fm5b4oul6PTzZa42hVe5NJnPxxQ6z2Bs0JMulTw/r9f0WBGSCV4mi/kmeCPXUbrhU5iGsLWCLhM9uUA==
  -----END PRIVATE KEY-----`;
  // 这里用于自动化部署进行动态替换密钥
  const newPrivateKey = '-----BEGIN PRIVATE KEY-----[key]-----END PRIVATE KEY-----';
  if (!newPrivateKey.includes('[key]')) {
    privateKey = newPrivateKey;
  }

  const decrypt = new JSEncrypt();
  decrypt.setPrivateKey(privateKey);
  const secretInfo = decrypt.decryptLong(encryptSecretInfo);
  if (!secretInfo || secretInfo === 'nullnull') {
    return false;
  }
  localMemory.set('oauth2ClientSecretInfo', secretInfo);
  const encryption = new AesEncryption(aesParams);
  localStorage.setItem('oauth2ClientSecretInfo', encryption.encryptByAES(secretInfo));

  return true;
};

// interface SecretInfo {
//   secretKey?: string;
//   secretType?: string;
//   signKey?: string
// }

export function getSecretInfo() {
  const encryption = new AesEncryption(aesParams);
  const value = localMemory.get('oauth2ClientSecretInfo')?.value || encryption.decryptByAES(localStorage.getItem('oauth2ClientSecretInfo')) || '{}';
  return JSON.parse(value);
}
